package com.jhd.fuzhou.view.photo;

import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.core.content.FileProvider;
import androidx.exifinterface.media.ExifInterface;

import com.alibaba.fastjson.JSON;
import com.jhd.fuzhou.R;
import com.jhd.fuzhou.util.CustomToast;
import com.jhd.fuzhou.util.DateTime;
import com.jhd.fuzhou.util.EditTextView;
import com.jhd.fuzhou.util.GetImageByUrl;
import com.jhd.fuzhou.util.TextDialog;
import com.jhd.fuzhou.util.UploadFile;
import com.jhd.fuzhou.view.login.BaseActivity;
import com.jhd.fuzhou.view.login.SignActivity;
import com.jhd.fuzhou.vo.SuperviseEnclosureVo;
import com.jhd.fuzhou.vo.SupervisionInspectionPhotoVo;
import com.jhd.fuzhou.vo.Upload;

import net.zigin.commons.util.StringUtil;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static com.jhd.fuzhou.util.DateTime.setTime;
import static com.jhd.fuzhou.util.TimeUtil.getTimeDialog;
import static com.jhd.fuzhou.util.TimeUtil.getTimeDialog5;
import static com.jhd.fuzhou.view.login.MainActivity.supervisionInspectionVo;

@RequiresApi(api = Build.VERSION_CODES.Q)
public class ChoosePhotoActivity extends BaseActivity {

    private static final int REQUEST_CODE = 1;
    @BindView(R.id.tv_photo_num)
    TextView tv_photo_num;//照片编号
    @BindView(R.id.et_proveMatters)EditText et_proveMatters;//证明事项
    @BindView(R.id.tv_shootingTime)TextView tv_shootingTime;//拍摄时间
    @BindView(R.id.et_shootingLocation)EditText et_shootingLocation;//拍摄地点
    @BindView(R.id.et_photographer)EditText et_photographer;//拍摄人
    @BindView(R.id.tv_lawEnforcementPersonnel1)TextView tv_lawEnforcementPersonnel1;//执法人员1
    @BindView(R.id.tv_lawEnforcementCertificateNumber1)TextView tv_lawEnforcementCertificateNumber1;//执法人员1编号
    @BindView(R.id.tv_lawEnforcementPersonnel2)TextView tv_lawEnforcementPersonnel2;//执法人员2
    @BindView(R.id.tv_lawEnforcementCertificateNumber2)TextView tv_lawEnforcementCertificateNumber2;//执法人员2编号
    @BindView(R.id.iv_party_sign)ImageView iv_party_sign;//当事人签名
    @BindView(R.id.image)
    ImageView image;//照片
    GetImageByUrl getImageByUrl = new GetImageByUrl();
    private SupervisionInspectionPhotoVo supervisionInspectionPhotoVo;
    private Context context = this;
    private File sdcardTempFile;
    private String path;//拍照的路径
    private Upload upload4;
    private String type;
    private String data;
    private List<SupervisionInspectionPhotoVo> supervisionInspectionPhotoVoList;
    private Bitmap bitmap0;
    private String folder;

    @Override
    protected void loadViewLayout() {
        setContentView(R.layout.activity_choose_photo);
    }

    @Override
    protected void processLogic() {
        application.addDocActivity(this);
        onBack();
        bitmap0 = ((BitmapDrawable) iv_party_sign.getDrawable()).getBitmap();
        data = getIntent().getStringExtra("data");
        type = getIntent().getStringExtra("type");

        upload4 = supervisionInspectionVo.getUpload4();
        supervisionInspectionPhotoVoList = supervisionInspectionVo.getSupervisionInspectionPhotoVoList();
        if (supervisionInspectionPhotoVoList == null)
            supervisionInspectionPhotoVoList = new ArrayList<>();
        if (upload4 != null) {
            Bitmap bitmap = BitmapFactory.decodeFile(getExternalFilesDir(null).getPath() + "/Download/4.png");
            iv_party_sign.setImageBitmap(bitmap);
        }
        if (data == null) {//直接添加图片，直接跳转到Android自带拍照选图片的页面
            supervisionInspectionPhotoVo = new SupervisionInspectionPhotoVo();
            if ("0".equals(type)) {//上个页面点击添加,选择拍照
                takePhoto();
            } else if ("1".equals(type)) {//上个页面点击添加,选择从相册选择
                selectFromGallery();
            }
        } else {
            supervisionInspectionPhotoVo = JSON.parseObject(data, SupervisionInspectionPhotoVo.class);
            setView(supervisionInspectionPhotoVo);
        }
        supervisionInspectionPhotoVo.setDocTemplateUrl(getIntent().getStringExtra("photoTemplateUrl"));
    }

    /**
     * 拍照
     */
    private void takePhoto() {
        folder = getExternalFilesDir(null).getPath() + "/Download/photo/";
        File folderFile = new File(folder);
        path = folder + "test.png";
        sdcardTempFile = new File(path);
        if (!folderFile.exists()) {
            folderFile.mkdirs();
        }
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, FileProvider.getUriForFile(context, "com.jhd.fuzhou.fileprovider", sdcardTempFile));
        } else {
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(sdcardTempFile));
        }
        startActivityForResult(intent, 101);

    }

    /**
     * 从相册选取照片
     */
    private void selectFromGallery() {
        folder = getExternalFilesDir(null).getPath() + "/Download/photo/";
        path = folder + "test.png";
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_PICK);
        intent.setType("image/*");
        startActivityForResult(intent, 102);
    }

    /*将照片信息显示到控件上*/
    private void setView(SupervisionInspectionPhotoVo supervisionInspectionPhotoVo) {
        tv_photo_num.setText(supervisionInspectionPhotoVo.getPhotoNum());
        et_proveMatters.setText(supervisionInspectionPhotoVo.getProveMatters());
        tv_shootingTime.setText(setTime(supervisionInspectionPhotoVo.getShootingTime()));
        EditTextView.TextViewChange(tv_shootingTime,context);
        et_shootingLocation.setText(supervisionInspectionPhotoVo.getShootingLocation());
        et_photographer.setText(supervisionInspectionPhotoVo.getPhotographer());
        tv_lawEnforcementPersonnel1.setText(supervisionInspectionPhotoVo.getLawEnforcementPersonnel1());
        tv_lawEnforcementCertificateNumber1.setText(supervisionInspectionPhotoVo.getLawEnforcementCertificateNumber1());
        tv_lawEnforcementPersonnel2.setText(supervisionInspectionPhotoVo.getLawEnforcementPersonnel2());
        tv_lawEnforcementCertificateNumber2.setText(supervisionInspectionPhotoVo.getLawEnforcementCertificateNumber2());
        EditTextView.TextViewChange(tv_lawEnforcementPersonnel1,context);
        EditTextView.TextViewChange(tv_lawEnforcementCertificateNumber1,context);
        EditTextView.TextViewChange(tv_lawEnforcementPersonnel2,context);
        EditTextView.TextViewChange(tv_lawEnforcementCertificateNumber2,context);
        getImageByUrl.setImage(iv_party_sign, supervisionInspectionPhotoVo.getPartySignatureUrl());
    }

    @OnClick({R.id.btn_submit, R.id.btn_back, R.id.iv_party_sign, R.id.tv_choose_image, R.id.tv_take_photo,R.id.et_proveMatters,
            R.id.et_shootingLocation,R.id.et_photographer,R.id.tv_shootingTime})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_submit://判断所有的东西是不是都填了
                if(et_proveMatters.getText().toString().equals("")){
                    CustomToast.showText(context,"请输入证明事项!",3000,0,0).show();
                    break;
                }
                if(tv_shootingTime.getText().toString().equals("请选择")){
                    CustomToast.showText(context,"请选择拍摄时间!",3000,0,0).show();
                    break;
                }
                if(et_shootingLocation.getText().toString().equals("")){
                    CustomToast.showText(context,"拍摄地点!",3000,0,0).show();
                    break;
                }
                if(et_photographer.getText().toString().equals("")){
                    CustomToast.showText(context,"请输入拍摄人!",3000,0,0).show();
                    break;
                }
                Bitmap bitmap1 = ((BitmapDrawable) iv_party_sign.getDrawable()).getBitmap();
                if (bitmap1 == bitmap0) {
                    supervisionInspectionVo.setSign4(false);
                } else {
                    supervisionInspectionVo.setSign4(true);
                }
                Intent printIntent = new Intent(context, PhotoPrintActivity.class);
                supervisionInspectionPhotoVo.setShootingLocation(et_shootingLocation.getText().toString());
                supervisionInspectionPhotoVo.setProveMatters(et_proveMatters.getText().toString());
                supervisionInspectionPhotoVo.setShootingTime(DateTime.setDate(tv_shootingTime.getText().toString()));
                supervisionInspectionPhotoVo.setPhotographer(et_photographer.getText().toString());
                if (data != null) {
                    int position = Integer.valueOf(getIntent().getStringExtra("position"));
                    supervisionInspectionPhotoVoList.remove(position);
                    supervisionInspectionPhotoVoList.add(position, supervisionInspectionPhotoVo);
                    printIntent.putExtra("position", String.valueOf(position));
                } else {
                    List<SuperviseEnclosureVo> superviseEnclosureVoList;
                    if(type.equals("专项监督")){
                        superviseEnclosureVoList= supervisionInspectionVo.getDocumentAttachmentList();
                    }else{
                        superviseEnclosureVoList= supervisionInspectionVo.getSuperviseEnclosureVoList();
                    }
                    if(superviseEnclosureVoList!=null){
                        int size=superviseEnclosureVoList.size();
                        //将非图片笔录的数量删除
                        for (SuperviseEnclosureVo superviseEnclosureVo : superviseEnclosureVoList) {
                            if("现场笔录".equals(superviseEnclosureVo.getEnclosureName())||"监督意见书".equals(superviseEnclosureVo.getEnclosureName())||"询问笔录".equals(superviseEnclosureVo.getEnclosureName())){
                                size--;
                            }
                        }
                        //如果照片和文书数量一致，直接添加，否则将最后加入的图片删除再添加
                        if(supervisionInspectionPhotoVoList.size()==size) {
                            supervisionInspectionPhotoVoList.add(supervisionInspectionPhotoVo);
                        }else{
                            if(supervisionInspectionPhotoVoList.size()>0){
                                supervisionInspectionPhotoVoList.remove(supervisionInspectionPhotoVoList.size()-1);
                            }
                            supervisionInspectionPhotoVoList.add(supervisionInspectionPhotoVo);
                        }

                    }else{
                        if(supervisionInspectionPhotoVoList.size()>0){
                            supervisionInspectionPhotoVoList.remove(supervisionInspectionPhotoVoList.size()-1);
                        }
                        supervisionInspectionPhotoVoList.add(supervisionInspectionPhotoVo);
                    }
                    printIntent.putExtra("position", String.valueOf(supervisionInspectionPhotoVoList.size() - 1));
                }
                supervisionInspectionVo.setSupervisionInspectionPhotoVoList(supervisionInspectionPhotoVoList);
                printIntent.putExtra("supervisionType", getIntent().getStringExtra("supervisionType"));
                startActivity(printIntent);
                break;
            case R.id.btn_back:
                onBack();
                break;
            case R.id.et_proveMatters:
                TextDialog.showDialog(context,"证明事项",et_proveMatters);
                break;
            case R.id.et_shootingLocation:
                TextDialog.showDialog(context,"拍摄地点",et_shootingLocation);
                break;
            case R.id.et_photographer:
                TextDialog.showDialog(context,"拍摄人",et_photographer);
                break;
            case R.id.tv_shootingTime:
                getTimeDialog5(tv_shootingTime,context);
                break;
            case R.id.iv_party_sign:
                Intent intent = new Intent(context, SignActivity.class);
                intent.putExtra("position", "1");
                startActivityForResult(intent, 103);
                break;
            case R.id.tv_choose_image://从相册选择
                selectFromGallery();
                break;
            case R.id.tv_take_photo://拍照
                takePhoto();
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable @org.jetbrains.annotations.Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            /**
             * 根据路径获取数据
             * */
            case 101:
                if (resultCode == RESULT_OK && sdcardTempFile.exists()) {
                    try {
                        //如果需要上传照片到服务器，上传方法写这里既可
                        FileInputStream inputStream = new FileInputStream(sdcardTempFile);
                        Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                        image.setImageBitmap(bitmap);
                        getImageAttribute(bitmap,path);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                break;
            case 102:
                ContentResolver contentResolver = getContentResolver();
                if (data != null) {
                    //如果需要把选取的图片进行上传服务器，请把下面代码注释解开，因为这样 才能获取到文件URI转的文件路径~方便上传的时候使用
                    //Uri uri = data.getData();
                    //使用工具类获取绝对路径
                    //String path = getFilePathFromContentUri(uri, contentResolver);
                    //File sdcardTempFile = new File(path);
                    //if (resultCode == RESULT_OK && sdcardTempFile.exists()) {
                    if (resultCode == RESULT_OK) {
                        //显示在我们UI上
                        Bitmap bitmap = null;
                        try {
                            //如果需要上传照片到服务器，上传方法写这里既可
                            InputStream is=contentResolver.openInputStream(data.getData());
                            bitmap = BitmapFactory.decodeStream(is);
                            UploadFile.copyPhoto(bitmap,folder,"test.png",context);
                            image.setImageBitmap(bitmap);
                            getImageAttribute(bitmap,path);
                        } catch (FileNotFoundException e) {
                            e.printStackTrace();
                        }
                    }
                }
                break;
            case 103:
                if (resultCode == RESULT_OK) {
                    byte[] bis = data.getByteArrayExtra("signBitmap");
                    Bitmap bitmap = BitmapFactory.decodeByteArray(bis, 0, bis.length);
                    File files = new File(getExternalFilesDir(null).getPath() + "/Download/");
                    if (!files.exists()) files.mkdirs();
                    if (data.getStringExtra("position").equals("1")) {
                        iv_party_sign.setImageBitmap(bitmap);
                        File file = new File(getExternalFilesDir(null).getPath() + "/Download/4.png");
                        if (file.exists()) file.delete();
                        supervisionInspectionVo.setUpload4(null);
                        UploadFile.saveBitmapFile(context, bitmap, "Download/4.png");
                    }
                }
                break;
            default:
                break;
        }
    }

    private void getImageAttribute(Bitmap bitmap,String imagePath) {
        try {
            ExifInterface exifInterface = new ExifInterface(imagePath);
            String datetime = exifInterface.getAttribute(ExifInterface.TAG_DATETIME);// 拍摄时间
            String deviceName = exifInterface.getAttribute(ExifInterface.TAG_MAKE);// 设备品牌
            String deviceModel = exifInterface.getAttribute(ExifInterface.TAG_MODEL); // 设备型号
            /*String subjectLocation = exifInterface.getAttribute(ExifInterface.TAG_SUBJECT_LOCATION);//主题地址
            String lngValue = exifInterface.getAttribute(ExifInterface.TAG_GPS_LONGITUDE);
            String latRef = exifInterface.getAttribute(ExifInterface.TAG_GPS_LATITUDE_REF);
            String lngRef = exifInterface.getAttribute(ExifInterface.TAG_GPS_LONGITUDE_REF);*/
            //拍摄时间
            if (!StringUtil.isNullOrEmpty(datetime)) {
                tv_shootingTime.setText(DateTime.changeStyle(datetime));
                EditTextView.TextViewChange(tv_shootingTime,context);
            } else {
                tv_shootingTime.setText(setTime(new Date()));
            }
            tv_photo_num.setText(DateTime.getPhotoNum(new Date()));
            supervisionInspectionPhotoVo.setShootingTime(DateTime.setDate(tv_shootingTime.getText().toString()));
            supervisionInspectionPhotoVo.setPhotoNum(tv_photo_num.getText().toString());
            et_shootingLocation.setText(supervisionInspectionVo.getRegisterAddress() == null ? "" : supervisionInspectionVo.getRegisterAddress());//拍摄地点
            et_photographer.setText(supervisionInspectionVo.getFirstSupervisorName());//拍摄人
            tv_lawEnforcementPersonnel1.setText(supervisionInspectionVo.getFirstSupervisorName());//执法人员1
            tv_lawEnforcementCertificateNumber1.setText(supervisionInspectionVo.getFirstSupervisorNo());//执法人员1编号
            tv_lawEnforcementPersonnel2.setText(supervisionInspectionVo.getSecondSupervisorName());//执法人员2
            tv_lawEnforcementCertificateNumber2.setText(supervisionInspectionVo.getSecondSupervisorNo());//执法人员2编号
            supervisionInspectionPhotoVo.setLawEnforcementPersonnel1(tv_lawEnforcementPersonnel1.getText().toString());
            supervisionInspectionPhotoVo.setLawEnforcementCertificateNumber1(tv_lawEnforcementCertificateNumber1.getText().toString());
            supervisionInspectionPhotoVo.setLawEnforcementPersonnel2(tv_lawEnforcementPersonnel2.getText().toString());
            supervisionInspectionPhotoVo.setLawEnforcementCertificateNumber2(tv_lawEnforcementCertificateNumber2.getText().toString());
            supervisionInspectionPhotoVo.setPhotographer(et_photographer.getText().toString());
            EditTextView.TextViewChange(tv_lawEnforcementPersonnel1,context);
            EditTextView.TextViewChange(tv_lawEnforcementCertificateNumber1,context);
            EditTextView.TextViewChange(tv_lawEnforcementPersonnel2,context);
            EditTextView.TextViewChange(tv_lawEnforcementCertificateNumber2,context);
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}